#include "mainform.h"
#include "ui_mainform.h"

mainForm::mainForm(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::mainForm)
{
    m_ui->setupUi(this);

    fW = new firstWidget( this );
    txtW = new txtForm( this );
    csvW = new csvForm( this );
    htmW = new htmlForm( this );
    prgW = new progressForm( this );
    finW = new finishForm( this );
    prView = new previewForm( this );

    m_ui->stackedWidget->addWidget( fW );
    m_ui->stackedWidget->addWidget( txtW );
    m_ui->stackedWidget->addWidget( csvW );
    m_ui->stackedWidget->addWidget( htmW );
    m_ui->stackedWidget->addWidget( prView );
    m_ui->stackedWidget->addWidget( prgW );
    m_ui->stackedWidget->addWidget( finW );

    m_ui->stackedWidget->setCurrentWidget( fW );
    m_ui->prevButton->hide();

    connect( this, SIGNAL( stepMade(int) ), prgW, SLOT( progressChange(int) ) );
}

void mainForm::setTreeWidget( QTreeWidget * tree )
{
    treeWidget = tree;
    progress = 0;
    total = 0;

    QTreeWidgetItemIterator it( treeWidget );
    while (*it)
    {
        total++;
        ++it;
    }

    if ( total > 300 )
        prgW->setWaiting( false );
}

mainForm::~mainForm()
{
    delete m_ui;
    delete fW;
    delete txtW;
    delete csvW;
    delete htmW;
}

void mainForm::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void mainForm::fillPreview()
{
    saveToFile( fileName, 0 );

    QFile file(fileName);
    if ( file.open(QIODevice::ReadOnly) )
    {
        prView->setText( file.readAll() );
        file.close();
    }
}

void mainForm::on_nextButton_clicked()
{
    if ( m_ui->stackedWidget->currentWidget() == fW )        // after first page
    {
        fileName = fW->getFileName();
        switch ( fW->getSelectedMode() )
        {
            case 0:
            {
                m_ui->stackedWidget->setCurrentWidget( txtW );
                break;
            }
            case 1:
            {
                m_ui->stackedWidget->setCurrentWidget( csvW );
                break;
            }
            case 2: // xml
            {
                m_ui->stackedWidget->setCurrentWidget( prView );
                fillPreview();
                break;
            }
            case 3:
            {
                m_ui->stackedWidget->setCurrentWidget( htmW );
                break;
            }
        }
        m_ui->prevButton->show();
    }
    else if ( m_ui->stackedWidget->currentWidget() == txtW ||
              m_ui->stackedWidget->currentWidget() == csvW ||
              m_ui->stackedWidget->currentWidget() == htmW ) // after second page
    {
        m_ui->stackedWidget->setCurrentWidget( prView );
        fillPreview();
    }
    else if ( m_ui->stackedWidget->currentWidget() == prView ) // after 3 page
    {
        m_ui->stackedWidget->setCurrentWidget( prgW );
        saveToFile( fileName, 1 );
    }
    else if ( m_ui->stackedWidget->currentWidget() == prgW ) // after 4 page
    {
        m_ui->stackedWidget->setCurrentWidget( finW );
        m_ui->prevButton->hide();
        m_ui->nextButton->setText( "Finish" );
        m_ui->cancelButton->hide();
    }
    else if ( m_ui->stackedWidget->currentWidget() == finW ) // after last page
    {
        accept();
    }
}

void mainForm::on_prevButton_clicked()
{
    if ( m_ui->stackedWidget->currentWidget() == txtW ||     // choice
         m_ui->stackedWidget->currentWidget() == csvW ||
         m_ui->stackedWidget->currentWidget() == htmW )
    {
        m_ui->stackedWidget->setCurrentWidget( fW );
        m_ui->prevButton->hide();
    }
    else if ( m_ui->stackedWidget->currentWidget() == prView ) // preview
    {
        switch ( fW->getSelectedMode() )
        {
        case 0:
            {
                m_ui->stackedWidget->setCurrentWidget( txtW );
                break;
            }
        case 1:
            {
                m_ui->stackedWidget->setCurrentWidget( csvW );
                break;
            }
        case 2: // xml
            {
                m_ui->stackedWidget->setCurrentWidget( fW );
                break;
            }
        case 3:
            {
                m_ui->stackedWidget->setCurrentWidget( htmW );
                break;
            }
        }
    }
}

void mainForm::on_cancelButton_clicked()
{
    switch( QMessageBox::warning( this, "Export",
                                  "Do you really want to cancel export?",
                                  "Yes",
                                  "No", 0, 0, 1 ) )
    {
    case 1:
        {
            return;
        }
    }

    if ( QFileInfo(fileName).exists() )
        QFile::remove( fileName );
    reject();
}

// --------------------------------- export sector ----------------------------------------
void mainForm::saveToFile( QString& expFileName, int op )
{
    if ( !expFileName.isEmpty() )
    {
        if ( expFileName.right(3) == "txt" )
            save_to_txt_file( expFileName, op );
        if ( expFileName.right(3) == "xml" )
            save_to_xml_file( expFileName, op );
        if ( expFileName.right(3) == "csv" )
            save_to_csv_file( expFileName, op );
        if ( expFileName.right(4) == "html" )
            save_to_html_file( expFileName, op );

        if ( op == 1 )
            on_nextButton_clicked();
    }
}

void mainForm::save_to_txt_file( QString &_fileName, int op )
{
    QFile file(_fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << "Listing creator v. 1.5\n";
    out << QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss");
    out << "\n";
    out << "\n";

    for ( int i = 0; i < treeWidget->columnCount(); i++ )
        out << treeWidget->headerItem()->text(i) + "\t";
    out << "\n";
    out << "\n";

    QString indentStr;
    for ( int i = 1; i < txtW->getTxtIndent(); i++ )
        indentStr += " ";

    QTreeWidgetItemIterator it( treeWidget );
    while (*it)
    {
        QString strToFile;
        int spaceNum = getParentCount( *it );
        // make indent in begining
        for ( int i = 0; i < spaceNum; i++ )
            strToFile.append( indentStr );

        for ( int i = 0; i < treeWidget->columnCount(); i++ )
        {
            QString _value;
            if ( i == 0 && txtW->txt83format() )
                _value = (*it)->text(20);
            else
                _value = (*it)->text(i);

            int mode = txtW->getTxtOutputFormat();
            switch( mode )
            {
            case 0:
                {
                    _value.replace( '/', '\\' );
                    break;
                }
            case 1:
                {
                    _value.replace( '\\', '/' );
                    break;
                }
            }

            strToFile.append( _value );
            strToFile.append( '\t' );

            if ( op == 1 )
            {
                progress++;
                emit stepMade( progress/total*100 );
            }
        }
        strToFile.append('\n');

        out << strToFile;
        ++it;
    }

    file.close();
}

void mainForm::save_to_csv_file( QString &_fileName, int op )
{
    QFile file(_fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << "Listing creator v. 1.5\n";
    out << QDate::currentDate().toString("dd.MM.yyyy");
    out << "\n\n";

    QString delimiter = csvW->getCsvDelimiterChar();
    out << "Delimiter=" + delimiter;
    out << "\n\n";

    for ( int i = 0; i < treeWidget->columnCount(); i++ )
        out << treeWidget->headerItem()->text(i) + ";";
    out << "\n\n";

    QTreeWidgetItemIterator it( treeWidget );
    while (*it)
    {
        QString strToFile;
        int spaceNum = getParentCount( *it );
        for ( int i = 0; i < spaceNum; i++ )
            strToFile.append(delimiter);

        for ( int i = 0; i < treeWidget->columnCount(); i++ )
        {
            QString _value;
            if ( i == 0 && csvW->csv83format() )
                _value = (*it)->text(20);
            else
                _value = (*it)->text(i);

            switch( csvW->getCsvOutputFormat() )
            {
            case 0:
                {
                    _value.replace( '/', '\\' );
                    break;
                }
            case 1:
                {
                    _value.replace( '\\', '/' );
                    break;
                }
            }

            strToFile.append( _value );
            strToFile.append( delimiter );

            if ( op == 1 )
            {
                progress++;
                emit stepMade( progress/total*100 );
            }
        }
        strToFile.append('\n');

        out << strToFile;
        ++it;
    }

    file.close();
}

int mainForm::getParentCount( QTreeWidgetItem * itt )
{
    int result = 0;
    QTreeWidgetItem * temp = itt;
    while ( temp->parent() )
    {
        result++;
        temp = temp->parent();
    }

    return result;
}

void mainForm::save_to_xml_file( QString &_fileName, int op )
{
    const int Indent = 4;

    QDomDocument doc;
    QDomElement root = doc.createElement("Listing");
    doc.appendChild(root);
    QDomElement headers = doc.createElement("headers");
    QString headerStr;
    for ( int i = 0; i < treeWidget->columnCount(); i++ )
         headerStr.append( treeWidget->headerItem()->text(i).replace(" ", "_" ) + ";" );
    headers.setAttribute( "names", headerStr );
    root.appendChild( headers );

    QTreeWidgetItemIterator it( treeWidget );
    while (*it)
    {
        QTreeWidgetItem * lItem = *it;
        if ( !isItemFolder(lItem) )
        {
            QDomElement _fileElement = doc.createElement("file");
            if ( lItem->parent() )
            {
                QDomElement element = domElementList.value( lItem->parent() );
                if ( element.isElement() )
                    element.appendChild(_fileElement);
                else
                    root.appendChild(_fileElement);
            }
            else
                root.appendChild(_fileElement);

            _fileElement.setAttribute ( "Name", lItem->text(0) );

            for ( int i = 1; i < treeWidget->columnCount(); i++)
            {
                if ( !lItem->text(i).isEmpty() )
                {
                    QDomElement _createDate = doc.createElement( treeWidget->headerItem()->text(i).replace(" ", "_") );
                    _fileElement.appendChild(_createDate);
                    QDomText _createDateText = doc.createTextNode( lItem->text(i) );
                    _createDate.appendChild( _createDateText );
                }
            }
            domElementList.insert( lItem, _fileElement );
        }
        else
        {
            QDomElement _folder = doc.createElement("folder");

            if ( lItem->parent() )
            {
                QDomElement element = domElementList.value( lItem->parent() );
                if ( element.isElement() )
                    element.appendChild(_folder);
                else
                    root.appendChild(_folder);
            }
            else
                root.appendChild(_folder);

            _folder.setAttribute ( "Name", lItem->text(0) );
            for ( int i = 1; i < treeWidget->columnCount(); i++ )
            {
                if ( !lItem->text(i).isEmpty() )
                    _folder.setAttribute( treeWidget->headerItem()->text(i).replace(" ", "_" ), lItem->text(i) );
            }

            domElementList.insert( lItem, _folder );
        }
        ++it;

        if ( op == 1 )
        {
            progress++;
            emit stepMade( progress/total*100 );
        }
    }

    QFile file(_fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    doc.save(out, Indent);
    file.close();
}

void mainForm::save_to_html_file( QString &_fileName, int op )
{
    QFile file(_fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << "<HTML><HEAD>\n";
    out << "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1251\">\n";
    out << "<TITLE>Listing creator v. 1.5  ";
    out << QDate::currentDate().toString("dd.MM.yyyy");
    out << "</TITLE>\n";
    if ( htmW->htmlCss() )
    {
        out << "<link rel=\"stylesheet\" type=\"text/css\" href=\"";
        out << htmW->getCssFile();
        out << "\">\n";
    }
    out << "</head>\n";

    if ( !htmW->htmlColors() )
        out << "<BODY>\n";
    else
        out << "<BODY link=#" + htmW->getLinkColor() + ">\n";

    if ( !htmW->htmlColors() )
    {
        out << "<H1 align=center>Listing creator v. 1.5</H1>\n";
    }
    else
    {
        QString toStd = QString("<H1 align=center><FONT color=#%1>Listing creator v. 1.5</FONT></H1>\n").
                        arg(htmW->getHeaderColor());
        out << toStd;
    }


    // main part
    out << "<P style=\"TEXT-ALIGN: justify; TEXT-INDENT: 15pt\">\n";
    out << "<TABLE border=1 width=\"90%\" align=left>\n";
    out << "<TBODY>\n";
    out << "<TR>\n";

    for ( int i = 0; i < treeWidget->columnCount(); i++ )
    {
        out << "<TD>\n";
        if ( !htmW->htmlColors() )
            out << "<P align=center>" + treeWidget->headerItem()->text(i) + "</P></TD>\n";
        else
        {
            QString toStd = "<P align=center><FONT color=#" + htmW->getTextColor() + ">";
            toStd += treeWidget->headerItem()->text(i);
            toStd += "</FONT></P></TD>\n";;
            out << toStd;
        }
    }
    out << "</TR>\n";

    QTreeWidgetItemIterator it( treeWidget );
    while (*it)
    {
        QString preStr;
        // make indent in begining
        for ( int i = 0; i < getParentCount( *it ); i++ )
            preStr.append( "&nbsp;&nbsp;&nbsp;&nbsp;" );

        out << "<TR>\n";
        for ( int i = 0; i < treeWidget->columnCount(); i++ )
        {
            if ( !htmW->htmlColors() )
                out << "<TD>\n";
            else
                out << "<TD><FONT color=#" + htmW->getTextColor() + ">\n";
            QString _value;
            if ( i == 0 )
            {
                QString formattedName = (*it)->text(i);
                if ( htmW->html83format() )
                    formattedName = (*it)->text(20);

                _value = preStr + formattedName;

                if ( htmW->htmlFilesLinks() && (*it)->text(22) == "file" )
                    _value = preStr + "<A href=\"" + (*it)->text(26) + "\">" + formattedName + "</A>";

                if ( htmW->htmlFoldersLinks() && (*it)->text(22) == "folder" )
                    _value = preStr + "<A href=\"" + (*it)->text(26) + "\">" + formattedName + "</A>";
            }
            else
                _value = (*it)->text(i);

            int mode = htmW->getHtmlOutputFormat();
            switch( mode )
            {
            case 0:
                {
                    _value.replace( '/', '\\' );
                    break;
                }
            case 1:
                {
                    _value.replace( '\\', '/' );
                    break;
                }
            }
            _value.replace( "<\\A>", "</A>" );

            if ( !_value.isEmpty() )
            {
                if ( !htmW->htmlColors() )
                    out << _value << "</TD>\n";
                else
                    out << _value << "</FONT></TD>\n";
            }
            else
            {
                out << "&nbsp</TD>\n";
                if ( !htmW->htmlColors() )
                    out << "&nbsp</TD>\n";
                else
                    out << "&nbsp</FONT></TD>\n";
            }
        }
        out << "</TR>\n";
        ++it;

        if ( op == 1 )
        {
            progress++;
            emit stepMade( progress/total*100 );
        }
    }

    out << "</TBODY></TABLE></P>";
    out << "</BODY></HTML>";
    file.close();
}

bool mainForm::isItemFolder( QTreeWidgetItem * item )
{
    if ( item->text(22) == "folder" )
        return true;
    return false;
}
